package co.edu.unal.geditor.view;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JPanel;

import co.edu.unal.geditor.controller.App;
import co.edu.unal.geditor.model.Drawing;
import co.edu.unal.geditor.model.DrawingListener;
import co.edu.unal.geditor.model.GraphElement;
import co.edu.unal.geditor.view.tools.Tool;

public class Canvas extends JPanel implements DrawingListener {
	private static final long serialVersionUID = 1L;

	public Canvas() {
		setBackground(Color.WHITE);

		addInputListeners();
	}

	public void init() {
		Drawing doc = App.getInstance().getDrawing();
		doc.addListener(this);
	}

	private void addInputListeners() {
		addMouseListener();
		addMouseMotionListener();
		addKeyboardListener();
	}

	private void addMouseListener() {
		addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent me) {
				m_activeTool.processMousePressed(me.getPoint());

			}

			@Override
			public void mouseReleased(MouseEvent me) {
				m_activeTool.processMouseReleased(me.getPoint());
			}

		});
	}

	private void addMouseMotionListener() {
		addMouseMotionListener(new MouseMotionAdapter() {
			@Override
			public void mouseDragged(MouseEvent me) {
				m_activeTool.processMouseDragged(me.getPoint());
			}

			@Override
			public void mouseMoved(MouseEvent me) {
				
				m_activeTool.processMouseMoved(me.getPoint());
				// App.getInstance().getMainFrame().setStatus("X: " +
				// me.getPoint().x + " - Y: " + me.getPoint().y);
			}
		});
	}

	private void addKeyboardListener() {
		// TODO
	}

	public void paint(Graphics g) {
		// paint the background
		super.paint(g);

		// paint the elements
		App.getInstance().paint(g);
		
	}
	


	public void update() {
		repaint();
	}

	public void processDrawingEvent(DrawingEvent de) {
		update();
	}

	public GraphElement getActiveFeedbackGraphElement() {
		return activeFeedbackGraphElement;
	}

	public void setActiveFeedbackGraphElement(
			GraphElement activeFeedbackGraphElement) {
		this.activeFeedbackGraphElement = activeFeedbackGraphElement;
	}

	// PRE-CONDITION: tool != null
	// POST-CONDITION: active tool changed
	public void setActiveTool(Tool tool) {
		assert tool != null;

		m_activeTool = tool;
	}
	public Tool getActiveTool() {
		return m_activeTool;
	}

	private Tool m_activeTool;
	
	
	private GraphElement activeFeedbackGraphElement;
	


	
}
